package org.regotto.basics.bfs;

import org.regotto.basics.dataStruct.Pii;
import org.regotto.common.Utils;

import java.util.Scanner;

/**
 * 走迷宫, n * m 求最短路, 0 可走, 1 不可走
 */
public class Mazes {

    static int n, m, h, t;
    static int[][] g = new int[10][10], d = new int[10][10];
    static Pii[] q = new Pii[10 * 10];

    public static int bfs() {
        q[0] = new Pii(0, 0);
        Utils.full(d, -1);
        d[0][0] = 0;
        int[] dx = new int[]{0, 1, 0, -1}, dy = new int[]{1, 0, -1, 0};
        while (h <= t) {
            Pii tmp = q[h++];
            for (int i = 0; i < 4; i++) {
                int x = tmp.x + dx[i], y = tmp.y + dy[i];
                if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] != 1 && d[x][y] == -1) {
                    d[x][y] = d[tmp.x][tmp.y] + 1;
                    q[++t] = new Pii(x, y);
                }
            }
        }
        return d[n - 1][m - 1];
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                g[i][j] = sc.nextInt();
            }
        }
        System.out.println(bfs());
    }

}
